﻿using Newtonsoft.Json;
using System;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http.Filters;

namespace Inovout.Cloud.Web.Http
{
    public class CloudExceptionFilter : IExceptionFilter
    {
        public Task ExecuteExceptionFilterAsync(HttpActionExecutedContext actionExecutedContext, CancellationToken cancellationToken)
        {
            actionExecutedContext.Response = new HttpResponseMessage(HttpStatusCode.InternalServerError);

            actionExecutedContext.Response.Content = new StringContent(
                JsonConvert.SerializeObject(new { error = new { Message = actionExecutedContext.Exception.Message } })
                );
            TaskCompletionSource<object> tcs = new TaskCompletionSource<object>();
            tcs.SetResult(null);
            return tcs.Task;
        }

        public bool AllowMultiple
        {
            get { return false; }
        }
    }
}
